import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/login",
    },
    {
      path: "/admin",
      name: "home",
      component: () => import("@/views/home/index.vue"),
      meta: { isLogin: true },
      redirect: "/admin/form",
      children: [
        {
          path: "/admin/capital",
          name: "capital",
          component: () => import("@/views/home/capital/capital.vue"),
          redirect: "/admin/form",
          children: [
            {
              path: "/admin/form",
              name: "form",
              component: () => import("../views/home/capital/form/form.vue"),
            },
            {
              path: "/admin/flowTo",
              name: "flowTo",
              component: () => import("../views/home/capital/flowTo/flowTo.vue"),
            },
            {
              path: "/admin/source",
              name: "source",
              component: () => import("../views/home/capital/source/source.vue"),
            },
          ],
        },
        {
          path: "/admin/system",
          name: "system",
          component: () => import("@/views/home/system/system.vue"),
          redirect: "/admin/user",
          children: [
            {
              path: "/admin/user",
              name: "user",
              component: () => import("../views/home/system/user/user.vue"),
            },
          ],
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/login.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      name: "not",
      component: () => import("@/views/NotFound.vue"),
    },
  ],
});

// 全局路由前置守卫
router.beforeEach((to, from) => {
  // 判断路由meta中的isLogin字段
  if (to.meta.isLogin) {
    // 为真需要判断是否有token
    const token = localStorage.getItem("token");
    // 如果没有token 去到登录页面
    if (!token) return { name: "login" };
    return true;
  } else {
    return true;
  }
});

export default router;
